#pragma once

#include <iostream>
#include <unistd.h>
using namespace std;

int NextTask()
{
    return rand() % 3;
}

// 函数指针  用回调函数的形式来传给子进程，即指派任务给子进程
typedef void (*work_t)(int);
typedef void (*task_t)(int, pid_t);
void PrintLog(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd << ", Print log task" << endl;
}
void ReloadConf(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd << ", Reload conf task" << endl;
}
void ConnectMysql(int fd, pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd << ", Connect mysql task" << endl;
}
task_t tasks[3] = {PrintLog, ReloadConf, ConnectMysql};
void worker(int fd)
{
    while (true)
    {
        uint32_t common_code = 0;
        ssize_t n = read(0, &common_code, sizeof(common_code));
        if (n == sizeof(common_code))
        {
            if (common_code >= 3)
                continue;                     // 读到的任务不存在 错误读取
            tasks[common_code](fd, getpid()); // 在函数指针表里 进行函数回调 来执行任务
        }
        // else if(n == 0)  读到末尾了，所以read的返回值是0
        else
        {
            std::cout << "sub process: " << getpid() << "quit now..." << std::endl;
            break;
        }
    }
}
